package com.leexuan.ordersystem.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.leexuan.ordersystem.beans.Admin;
import com.leexuan.ordersystem.beans.Customer;
import com.leexuan.ordersystem.beans.Order;
import com.leexuan.ordersystem.beans.OrderDetail;
import com.leexuan.ordersystem.beans.Product;
import com.leexuan.ordersystem.db.OrderDB;
import com.leexuan.ordersystem.forms.OrderForm;

public class AddOrderAction extends Action {

	public AddOrderAction() {
		super();
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		OrderForm fm = (OrderForm) form;

		HttpSession session = request.getSession();
		Admin admin = (Admin) (session.getAttribute("admin"));
		Customer customer = (Customer) (session.getAttribute("orderCustomer"));
		ArrayList arraylist = (ArrayList) (session.getAttribute("orderDetail"));

		OrderDB odb = new OrderDB();

		try {

			odb.getConnection();

			Order order = new Order();
			order.setAid(admin.getAid());
			order.setCid(customer.getCid());
			order.setDate(fm.getDate());
			order.setDdate(fm.getDdate());
			order.setDtype(fm.getDtype());
			order.setSum(fm.getSum());

			odb.addOrder(order);

			order = null;
			order = odb.getOrderNew();

			int oid = order.getOid();

			for (int i = 0; i < arraylist.size(); i++) {

				OrderDetail od = new OrderDetail();
				od.setOid(oid);
				od.setPid(((Product) arraylist.get(i)).getPid());
				od.setPrice(((Product) arraylist.get(i)).getPrice());
				od.setQuantity(((Product) arraylist.get(i)).getNum());
				od.setRemain(((Product) arraylist.get(i)).getNum());

				odb.getConnection();

				odb.addOrderDetail(od);

			}

			session.removeAttribute("orderDetail");
			session.removeAttribute("orderCustomer");

			return mapping.findForward("success");

		} catch (Exception e) {

			return (new ActionForward(mapping.getInput()));
		} finally {
			try {
				odb.closeConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
